<template>
  <div class="tabs-app">
    <el-row :gutter="20">
      <el-col :span="4">
        <el-input
          v-model="filterText"
          placeholder="请输入岗位名称"
          clearable
          @clear="handleSearchUserByDept"
        />
        <el-tree
          ref="tree"
          class="filter-tree"
          :data="deptData"
          :props="{
            children: 'children',
            label: 'name'
          }"
          :filter-node-method="filterNode"
          @node-click="handleSearchUserByDept"
        />
      </el-col>
      <el-col :span="20">
        <!-- 搜索表单 -->
        <el-form :inline="true" class="search-component">
          <el-form-item label="用户名">
            <el-input
              v-model="searchCondition.keyWord"
              placeholder="请输入用户名"
              clearable
            />
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="searchCondition.createTime"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right"
            />
          </el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="medium"
            @click="initUserTable"
          >搜索</el-button>
          <el-button
            type="warning"
            icon="el-icon-refresh"
            size="medium"
            @click="resetSearchCondition"
          >重置</el-button>
        </el-form>
        <!-- 操作按钮 -->
        <el-form :inline="true" class="operation-component">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="showAddUserForm"
          >新&nbsp;&nbsp;&nbsp;&nbsp;增</el-button>

          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteUser"
          >批量删除</el-button>
          <el-button
            type="warning"
            icon="el-icon-refresh-left"
            size="mini"
            @click="resetPasswordShowForm"
          >重设密码</el-button>
          <el-button
            type="success"
            icon="el-icon-download"
            size="mini"
            @click="exportUser"
          >批量导出</el-button>
        </el-form>
        <!-- 列表 -->
        <el-table
          ref="userTable"
          :data="tableData"
          highlight-current-row
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="username" label="姓名" width="width" />
          <el-table-column prop="gender" label="性别" width="width" sortable />
          <el-table-column prop="phone" label="手机号" width="width" />
          <el-table-column prop="email" label="邮箱" width="width" />
          <el-table-column prop="id" label="所部部门" width="width" />
          <el-table-column
            prop="enabled==1"
            label="状态"
            align="center"
            width="width"
          >
            <template slot-scope="{ row }">
              <el-switch
                v-model="row.enabled"
                :disabled="row.id === 1"
                active-color="#409EFF"
                inactive-color="#F56C6C"
                @change="changeEnabled(row)"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="创建时间"
            width="width"
            sortable
          />
          <el-table-column label="操作" width="width" align="center">
            <template slot-scope="{ row }">
              <el-button
                type="warning"
                icon="el-icon-edit"
                size="small"
                @click="showUpdateUserForm(row)"
              >修改</el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="small"
                :disabled="row.id === 1"
                @click="deleteUser(row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-pagination
          :current-page="page.current"
          :total="page.total"
          :page-size="page.size"
          :page-sizes="[1, 10, 20, 50, 100]"
          style="padding: 20px 0"
          layout="total,prev, pager, next, sizes,jumper"
          @current-change="initUserTable"
          @size-change="handleSizeChange"
        />
        <!-- 新增/修改表单 -->
        <el-dialog
          :title="user.id ? '修改用户' : '新增用户'"
          :visible.sync="dialogFormVisible"
          width="30%"
        >
          <el-form ref="userForm" :model="user" :rules="userRules" :inline="true" label-width="80px">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="user.username" />
            </el-form-item>
            <el-form-item label="性别">
              <el-radio v-model="user.gender" label="男">男</el-radio>
              <el-radio v-model="user.gender" label="女">女</el-radio>
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="user.phone" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="user.email" />
            </el-form-item>
            <el-form-item label="部门" prop="id">
              <el-select v-model="user.id" placeholder="请选择部门">
                <el-option
                  v-for="item in user.deptList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="岗位" prop="jobIds">
              <el-select
                v-model="user.jobIds"
                multiple
                collapse-tags
                placeholder="请选择岗位"
              >
                <el-option
                  v-for="item in user.jobList"
                  :key="item.jobIds"
                  :label="item.name"
                  :value="item.jobId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="角色" prop="ids">
              <el-select
                v-model="user.id"
                multiple
                collapse-tags
                placeholder="请选择角色"
              >
                <el-option
                  v-for="item in user.roleList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="状态">
              <el-radio v-model="user.enabled" label="true">有效</el-radio>
              <el-radio v-model="user.enabled" label="false">无效</el-radio>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveDialogForm">确 定</el-button>
          </div>
        </el-dialog>
        <!-- 充值密码表单 -->
        <el-dialog
          title="批量重设密码"
          :visible.sync="dialogFormResetVisible"
          center
          width="20%"
          height="20%"
        >
          <el-form :model="resetPasswordForm" :inline="true" align="center">
            <el-form-item label="新密码">
              <el-input
                v-model="resetPasswordForm.password"
                placeholder="请输入密码"
                show-password
              />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormResetVisible = false">取 消</el-button>
            <el-button type="primary" @click="resetPassword">确 定</el-button>
          </div>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import Config from '@/settings'
import { isvalidPhone } from '@/utils/validate'
export default {
  name: 'AdminUser',
  data() {
    // 自定义验证
    const validPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入电话号码'))
      } else if (!isvalidPhone(value)) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        callback()
      }
    }
    return {
      page: {
        total: 0, // 总记录数
        current: 1, // 当前页码
        size: 10, // 每页记录数
        orders: [{ column: 'id', asc: true }]
      },
      searchCondition: {
        createTime: [],
        keyWord: '',
        deptId: undefined
      },
      tableData: [], // 列表数据
      deptData: [], // 岗位树
      filterText: '',
      dialogFormVisible: false, // 是否展示新增/修改表单
      dialogFormResetVisible: false, // 是否展示重置密码表单
      selectedIds: [], // 所有选择的user的id的数组
      user: {
        id: undefined,
        username: '',
        gender: '男',
        phone: undefined,
        email: '',
        roleIds: [],
        jobIds: [],
        deptId: undefined,
        enabled: 'true',
        roleList: [],
        jobList: [],
        deptList: []
      }, // 当前要操作的user
      userRules: {
        username: [
          { required: true, message: '请输入用户名' },
          { min: 2, message: '长度至少为2个字符' }
        ],
        phone: [
          { required: true, validator: validPhone }
        ],
        email: [
          { required: true, message: '请输入邮箱地址' },
          { type: 'email', message: '请输入正确的邮箱地址' }
        ],
        deptId: [{ required: true, message: '请选择部门', trigger: 'change' }],
        jobIds: [{ required: true, message: '请选择岗位', trigger: 'change' }],
        roleIds: [{ required: true, message: '请选择角色', trigger: 'change' }]
      },
      resetPasswordForm: {
        password: ''
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  mounted() {
    this.initUserTable()
    this.initDeptTree()
  },
  methods: {
    async initUserTable(current = 1) {
      const { page, searchCondition } = this
      if (Number.isInteger(current)) {
        page.current = current
      }
      const result = await this.$API.user.pageQuery({ searchCondition, page })
      if (result.code === 200) {
        this.tableData = result.data.records
        this.page.current = result.data.current
        this.page.size = result.data.size
        this.page.total = result.data.total
      }
    },
    async initDeptTree() {
      const page = { current: 1, size: 9999 }
      const searchCondition = { keyWord: this.deptKeyWord }
      const result = await this.$API.dept.pageQuery({ searchCondition, page })
      if (result.code === 200) {
        this.deptData = result.data.records
      }
    },
    async changeEnabled(row) {
      const result = await this.$API.user.changeEnabled(
        row.id,
        row.enabled
      )
      if (result.code === 200) {
        this.$message({
          message: '设置状态成功',
          type: 'success',
          showClose: true,
          duration: Config.duration
        })
      }
    },
    resetSearchCondition() {
      this.searchCondition.createTime = []
      this.searchCondition.keyWord = ''
      this.initUserTable()
    },
    async deleteUser(row) {
      let ids = []
      if (row.id) {
        ids = [row.id]
      } else {
        ids = this.selectedIds
      }
      if (ids.length === 0) {
        this.$message({
          message: '请选择要操作的数据',
          type: 'warning',
          showClose: true,
          duration: Config.duration
        })
        return
      }
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const result = await this.$API.user.deleteUser(ids)
          if (result.code === 200) {
            this.$message({
              message: '删除成功',
              type: 'success',
              showClose: true,
              duration: Config.duration
            })
            this.initUserTable()
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    async showAddUserForm() {
      const result = await this.$API.user.queryUser()
      if (result.code === 200) {
        this.user = result.data
      }
      this.user.enabled = 'true'
      this.$nextTick(() => this.$refs.userForm.clearValidate())
      this.dialogFormVisible = true
    },
    async showUpdateUserForm(row) {
      const result = await this.$API.user.queryUser(row.id)
      if (result.code === 200) {
        this.user = result.data
        if (result.data.enabled) {
          this.user.enabled = 'true'
        } else {
          this.user.enabled = 'false'
        }
      }
      this.$nextTick(() => this.$refs.userForm.clearValidate())
      this.dialogFormVisible = true
    },
    saveDialogForm() {
      this.$refs.userForm.validate(async valid => {
        if (valid) {
          let code
          const { user } = this
          if (user.id) {
            const result = await this.$API.user.updateUser(user)
            code = result.code
          } else {
            const result = await this.$API.user.createUser(user)
            code = result.code
          }
          if (code === 200) {
            this.dialogFormVisible = false
            this.$message({
              message: '保存成功',
              type: 'success',
              showClose: true,
              duration: Config.duration
            })
          } else {
            this.$message({
              message: '保存失败',
              type: 'error',
              showClose: true,
              duration: Config.duration
            })
          }
          this.initUserTable()
        }
      })
    },
    /*
      列表选中状态发生改变的监听回调
    */
    handleSelectionChange(selection) {
      this.selectedIds = selection.map((item) => item.id)
    },
    /*
    处理pageSize发生改变的监听回调
    */
    handleSizeChange(pageSize) {
      this.page.size = pageSize
      this.initUserTable()
    },
    async exportUser() {
      await this.$API.user.exportUser(this.selectedIds)
    },
    resetPasswordShowForm() {
      if (this.selectedIds.length < 1) {
        this.$message({
          message: '请选择要操作的数据',
          type: 'warning',
          showClose: true,
          duration: Config.duration
        })
        return
      }
      this.resetPasswordForm.password = ''
      this.dialogFormResetVisible = true
    },
    async resetPassword() {
      const data = {
        password: this.resetPasswordForm.password,
        ids: this.selectedIds
      }
      const result = await this.$API.user.resetPassword(data)
      if (result.code === 200) {
        this.$message({
          message: '保存成功',
          type: 'success',
          showClose: true,
          duration: Config.duration
        })
      }
      this.dialogFormResetVisible = false
    },
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    handleSearchUserByDept(row) {
      if (row) {
        this.searchCondition.deptId = row.id
      } else {
        this.searchCondition.deptId = undefined
      }
      this.initUserTable()
    }
  }
}
</script>

<style scoped>
</style>
